package me.zhengjie.modules.hanzi.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.AiServiceConfig;
import me.zhengjie.modules.hanzi.service.AiServiceManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI服务测试控制器
 * 用于测试和调试AI服务配置
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "AI服务测试管理")
@RequestMapping("/api/ai-service")
@Slf4j
public class AiServiceTestController {

    private final AiServiceConfig aiServiceConfig;
    private final AiServiceManager aiServiceManager;

    /**
     * 获取AI服务配置信息
     */
    @GetMapping("/config")
    @Operation(summary = "获取AI服务配置信息")
    public ResponseEntity<Map<String, Object>> getConfig() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取配置的提供商列表
        List<String> providers = aiServiceConfig.getProviders();
        result.put("providers", providers);
        
        // 检查各个提供商的启用状态
        Map<String, Object> providerStatus = new HashMap<>();
        providerStatus.put("openai", aiServiceConfig.isProviderEnabled("openai"));
        providerStatus.put("deepseek", aiServiceConfig.isProviderEnabled("deepseek"));
        providerStatus.put("anthropic", aiServiceConfig.isProviderEnabled("anthropic"));
        providerStatus.put("local", aiServiceConfig.isProviderEnabled("local"));
        result.put("providerStatus", providerStatus);
        
        // 全局配置
        result.put("globalConfig", aiServiceConfig.getGlobal());
        
        return ResponseEntity.ok(result);
    }

    /**
     * 测试AI服务调用
     */
    @PostMapping("/test")
    @Operation(summary = "测试AI服务调用")
    public ResponseEntity<Map<String, Object>> testAiService(
            @Parameter(description = "测试提示词", example = "你好，请回复一个简短的问候")
            @RequestParam(value = "prompt", defaultValue = "你好，请用中文回复一个简短的问候") String prompt) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始测试AI服务调用，提示词: {}", prompt);
            
            long startTime = System.currentTimeMillis();
            String response = aiServiceManager.callAiService(prompt);
            long endTime = System.currentTimeMillis();
            
            result.put("success", true);
            result.put("prompt", prompt);
            result.put("response", response);
            result.put("responseTime", endTime - startTime);
            result.put("timestamp", System.currentTimeMillis());
            
            log.info("AI服务调用成功，响应时间: {}ms", endTime - startTime);
            
        } catch (Exception e) {
            log.error("AI服务调用失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 测试单个AI服务提供商
     */
    @PostMapping("/test/{provider}")
    @Operation(summary = "测试指定的AI服务提供商")
    public ResponseEntity<Map<String, Object>> testSpecificProvider(
            @Parameter(description = "服务提供商", example = "openai")
            @PathVariable String provider,
            @Parameter(description = "测试提示词", example = "你好")
            @RequestParam(value = "prompt", defaultValue = "你好，请用中文回复一个简短的问候") String prompt) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查提供商是否启用
            if (!aiServiceConfig.isProviderEnabled(provider)) {
                result.put("success", false);
                result.put("error", "AI服务提供商 " + provider + " 未启用或不存在");
                return ResponseEntity.ok(result);
            }
            
            log.info("开始测试AI服务提供商: {}, 提示词: {}", provider, prompt);
            
            // 临时修改提供商列表，只测试指定的提供商
            List<String> originalProviders = aiServiceConfig.getProviders();
            aiServiceConfig.setProviders(List.of(provider));
            
            try {
                long startTime = System.currentTimeMillis();
                String response = aiServiceManager.callAiService(prompt);
                long endTime = System.currentTimeMillis();
                
                result.put("success", true);
                result.put("provider", provider);
                result.put("prompt", prompt);
                result.put("response", response);
                result.put("responseTime", endTime - startTime);
                result.put("timestamp", System.currentTimeMillis());
                
                log.info("AI服务提供商 {} 调用成功，响应时间: {}ms", provider, endTime - startTime);
                
            } finally {
                // 恢复原始提供商列表
                aiServiceConfig.setProviders(originalProviders);
            }
            
        } catch (Exception e) {
            log.error("AI服务提供商 {} 调用失败", provider, e);
            result.put("success", false);
            result.put("provider", provider);
            result.put("error", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取AI服务健康状态
     */
    @GetMapping("/health")
    @Operation(summary = "获取AI服务健康状态")
    public ResponseEntity<Map<String, Object>> getHealthStatus() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> healthStatus = new HashMap<>();
        
        List<String> providers = List.of("openai", "deepseek", "anthropic", "local");
        String testPrompt = "ping";
        
        for (String provider : providers) {
            if (!aiServiceConfig.isProviderEnabled(provider)) {
                healthStatus.put(provider, Map.of(
                    "status", "disabled",
                    "message", "服务未启用"
                ));
                continue;
            }
            
            try {
                // 临时只测试当前提供商
                List<String> originalProviders = aiServiceConfig.getProviders();
                aiServiceConfig.setProviders(List.of(provider));
                
                try {
                    long startTime = System.currentTimeMillis();
                    aiServiceManager.callAiService(testPrompt);
                    long endTime = System.currentTimeMillis();
                    
                    healthStatus.put(provider, Map.of(
                        "status", "healthy",
                        "responseTime", endTime - startTime,
                        "message", "服务正常"
                    ));
                } finally {
                    aiServiceConfig.setProviders(originalProviders);
                }
                
            } catch (Exception e) {
                healthStatus.put(provider, Map.of(
                    "status", "unhealthy",
                    "message", e.getMessage()
                ));
            }
        }
        
        result.put("healthStatus", healthStatus);
        result.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(result);
    }
}